<template>
  <div class="page-container">
    <div class="in-container">
      <ApplicaCashSearchFrom
        :query="query"
        @reset="reset"
        @saveData="saveData"
        :tableData="tableData.data"
        ref="ApplicaCashSearchFromRef"
        @clearTableData="clearTableData"
        @onEarch="onEarch"
      ></ApplicaCashSearchFrom>
      <div class="btn-box"></div>
      <AppPageTable
        stripe
        :data="tableData.data"
        :autostyle="'height: calc(100% - 304px);'"
        :isPagination="true"
        :option="tableData.option"
        @cellClick="cellClick"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          width="60"
          label="序号"
          type="index"
          fixed="left"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="doccode"
          width="115"
          label="业务编号"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="blNo" width="115" label="提单号" align="center">
        </el-table-column>
        <el-table-column prop="feeName" align="center" label="费用类型">
        </el-table-column>
        <el-table-column
          prop="currency"
          align="center"
          label="币种"
          width="120"
        >
        </el-table-column>
        <el-table-column
          prop="createBy"
          align="center"
          label="请款人"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="totalmoney"
          align="center"
          label="金额"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="reqMoney"
          align="center"
          label="请款金额"
          width="115"
        >
        </el-table-column>
        <el-table-column
          prop="payMoney"
          align="center"
          label="付款金额"
          width="115"
        >
          <template #default="scope">
            <div
              v-if="
                scope.row.index === rowIndex &&
                scope.column.index === colIndex &&
                !checkIsDisabled
              "
            >
              <el-input
                v-model="scope.row.payMoney"
                :min="0"
                :max="scope.row.totalmoney"
                size="small"
                :precision="2"
                ref="verificationMoneyRef"
                @change="handleRowChange(scope.row, 'verificationMoney')"
                @blur="loseFocusInput"
                @input="scope.row.payMoney = validateNumber(scope.row.payMoney)"
              >
              </el-input>
            </div>
            <span v-else>{{ scope.row.payMoney }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="unPayMoney"
          align="center"
          label="未付款金额"
          width="115"
        >
        </el-table-column>
        <!-- <el-table-column prop="invoiceCode" align="center" label="发票号">
        </el-table-column>
        <el-table-column
          prop="invoiceDate"
          align="center"
          label="发票日期"
          width="140"
        >
          <template #default="scope">
            {{
              scope.row.invoiceDate
                ? scope.row.invoiceDate.substring(0, 10)
                : scope.row.invoiceDate
            }}
          </template>
        </el-table-column> -->
        <el-table-column prop="feeMemo" align="center" label="备注">
        </el-table-column>
      </AppPageTable>
    </div>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import ApplicaCashSearchFrom from './ApplicaCashSearchFrom.vue'

import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatNum } from '@/utils/format.ts'
import { validateNumber } from '@/utils/validate.js'
import bus from '@/utils/vueBus'
export default defineComponent({
  components: {
    AppPageTable,
    ApplicaCashSearchFrom
  },
  props: {
    doctype: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      //表格数据
      tableData: {
        data: [],
        option: useTableOption()
      },
      // 合计金额
      totalCount: {
        // 请款金额
        sumtotalmoney: 0,
        // 销帐金额
        sumverificationMoney: 0,
        // 未销金额
        unVerificationMoney: 0,
        // 已销金额
        hassumverificationMoney: 0
      },
      colIndex: -1,
      rowIndex: -1,
      exchangeRateData: [],
      query: {
        // 银行卡号
        bankAccount: '',
        // 银行账号名称
        bankAccountName: '',
        // 银行名称
        bankName: '',
        // 可销账金额
        canverificationMoney: '',
        // 审核状态 0草稿 1提交审核  2审核通过  -1驳回
        checkStatus: 0,
        // 付款币种
        currency: '',
        // 付款单号
        doccode: '',
        // 付款日期
        docdate: dayjs().format('YYYY-MM-DD'),
        // 费用单号
        balanceDoccode: '',
        // 收付类型:1 收款,0付款
        doctype: this.doctype,
        // 结算对象代码（左）
        entCode: '',
        // 结算对象名称（右）
        entFullname: '',
        // 结算对象Id
        entId: '',
        //汇率
        exchangeRate: '',
        // 销账币种
        feeCurrency: '',
        // 摘要
        memo: '',
        // 业务员Id
        salesId: '',
        // 业务员名称
        salesName: '',
        // 付款金额
        sumtotalmoney: '',
        // 已销金额
        sumverificationMoney: '',
        // 未销金额
        unVerificationMoney: '',
        //  审核人名称
        checkBy: '',
        // 录入人
        createBy: this.$store.getters['auth/getUser'].nickName,
        // 录入日期
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      }
    }
  },
  methods: {
    validateNumber,
    // 已销金额同步更新
    handleRowChange(row) {
      let maxMoney = Number(
        (parseFloat(row.reqMoney) - parseFloat(row.hasPayMoney)).toFixed(2)
      )
      row.payMoney = formatNum(row.payMoney, 2, 0, maxMoney)
      row.payMoney = row.payMoney ? Number(row.payMoney) : 0

      if (row.payMoney >= parseFloat(maxMoney)) {
        row.payMoney = parseFloat(maxMoney)
      }
      row.unPayMoney = Number(
        (parseFloat(maxMoney) - parseFloat(row.payMoney)).toFixed(2)
      )
      this.refreshCount([], 'searchChange')
    },
    // 输入框失去焦点
    loseFocusInput() {
      this.$refs.ApplicaCashSearchFromRef.jkl = false
      this.colIndex = -1
      this.rowIndex = -1
    },

    // 单元格点击
    cellClick({ row, column }) {
      // if (this.query.checkStatus == 1 || this.query.checkStatus == 2) {
      //   return;
      // }
      this.colIndex = column.index
      this.rowIndex = row.index
      this.$nextTick(() => {
        this.$refs.verificationMoneyRef.focus()
      })
    },

    // 删除销账
    async deleWriteOff() {
      if (!this.tableData.option.selected.length) {
        this.$message.warning('请选择数据')
        return
      }
      ElMessageBox.confirm('是否确定执行删除操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let newArray = []
        this.tableData.data.forEach((t) => {
          if (!this.tableData.option.selected.find((item) => t == item)) {
            newArray.push(t)
          }
        })
        this.tableData.data = newArray
        this.refreshCount([])
      })
    },
    // 选中的表格数据
    selectOver(selectTableData) {
      let CpoySelectTableData = JSON.parse(JSON.stringify(selectTableData))

      this.refreshCount(CpoySelectTableData, 'searchChange')
    },

    // 重置表格数据
    clearTableData() {
      this.tableData.data = []
      this.tableData.option.selected = []
    },

    refreshCount(selectTableData, changeType) {
      this.totalCount = {
        // 应付合计
        sumtotalmoney: 0,
        // 已销金额
        sumverificationMoney: 0,
        // 未销金额
        unVerificationMoney: 0,
        hassumverificationMoney: 0
      }
      this.tableData.data = this.mergeAndRemoveDuplicates(
        JSON.parse(JSON.stringify(selectTableData)),
        JSON.parse(JSON.stringify(this.tableData.data))
      )

      if (this.tableData.data.length) {
        this.$refs.ApplicaCashSearchFromRef.query.createBy =
          this.tableData.data[0].createBy
        this.$refs.ApplicaCashSearchFromRef.query.createTime = dayjs().format(
          'YYYY-MM-DD HH:mm:ss'
        )
      }

      for (const iterator of this.tableData.data) {
        const flag = 1
        this.totalCount.sumtotalmoney += iterator.reqMoney
          ? parseFloat(iterator.reqMoney) * flag
          : 0
        this.totalCount.sumverificationMoney += iterator.payMoney
          ? parseFloat(iterator.payMoney) * flag
          : 0
        this.totalCount.unVerificationMoney += iterator.unPayMoney
          ? parseFloat(iterator.unPayMoney) * flag
          : 0
        this.totalCount.hassumverificationMoney += iterator.hasPayMoney
          ? parseFloat(iterator.hasPayMoney) * flag
          : 0
      }

      var a =
        this.exchangeRateData[
          this.$refs.ApplicaCashSearchFromRef.query.feeCurrency + '' + 0
        ]
      var b =
        this.exchangeRateData[
          this.$refs.ApplicaCashSearchFromRef.query.currency + '' + 0
        ]

      let num =
        (b / a) * this.$refs.ApplicaCashSearchFromRef.query.sumtotalmoney

      if (num >= this.totalCount.sumverificationMoney) {
        this.$refs.ApplicaCashSearchFromRef.query.canverificationMoney = num
      } else {
        this.$refs.ApplicaCashSearchFromRef.query.canverificationMoney =
          this.totalCount.sumverificationMoney
      }

      this.$refs.ApplicaCashSearchFromRef.query.sumverificationMoney =
        this.totalCount.sumverificationMoney
      this.$refs.ApplicaCashSearchFromRef.query.unVerificationMoney =
        Math.trunc(
          this.totalCount.sumtotalmoney - this.totalCount.sumverificationMoney
        )

      // 当前核销金额合计
      if (changeType) {
        let sumverificationMoney = this.totalCount.sumverificationMoney
          ? this.totalCount.sumverificationMoney.toFixed(0)
          : 0
        this.$refs.ApplicaCashSearchFromRef.query.sumverificationMoney =
          sumverificationMoney
      }

      // this.$refs.ApplicaCashSearchFromRef.query.totalmoney = totalMoneySum;
    },

    // 合并数组并去重
    mergeAndRemoveDuplicates(arr1, arr2) {
      let hash = {}
      // 合并两个数组
      let newArr = arr1.concat(arr2)
      const mergedArr = newArr.reduce((item, next) => {
        hash[next.workfeeId]
          ? ''
          : (hash[next.workfeeId] = true && item.push(next))
        return item
      }, [])
      return mergedArr
    },

    // 选择的费用数据重新组合 data = this.tableData
    resetFeeList(data) {
      let feeList = []
      for (const iterator of data) {
        let obj = {}
        obj = {
          id: 0,
          reqMoney: iterator.reqMoney,
          payMoney: iterator.payMoney,
          unPayMoney: iterator.unPayMoney,
          feeMemo: iterator.feeMemo,
          docId: iterator.docId,
          workfeeId: iterator.workfeeId
        }
        if (iterator.id) {
          obj['id'] = iterator.id
        }
        feeList.push(obj)
      }
      return feeList
    },

    // 当前页面应收应付下的币种汇率
    async getExchangeRateData() {
      let res = await this.$http.get('/api/base/exchangerate/query', {
        IsIncome: this.query.doctype
      })
      res.content.map((item) => {
        this.exchangeRateData[item.currency + item.isIncome] = item.exchangeRate
      })
      // 应收或应付对账页面跳转
      if (this.$route.query.currency) {
        this.query.currency = this.$route.query.currency
        this.query.feeCurrency = this.$route.query.currency
        this.query.exchangeRate =
          this.exchangeRateData[
            this.$refs.ApplicaCashSearchFromRef.query.feeCurrency + 0
          ]
        let selectedIds = JSON.parse(this.$route.query.selectedIds)
          ? JSON.parse(this.$route.query.selectedIds)
          : []
        if (selectedIds instanceof String) {
          selectedIds = [selectedIds]
        }
        this.$http
          .post(`/api/docBalance/getFeeListByBalanceIds?feeStatus=0`, {
            idArray: selectedIds
          })
          .then((res) => {
            const tmp = res[0]
            this.query.entCode = tmp.entCode
            this.query.entFullname = tmp.entFullname
            this.query.entId = tmp.entId
            // this.$refs.applicationAddSearchFromRef.getBusDetail(tmp.entCode);  //根据endtCode查询无法获取到对应的数据
            this.$refs.ApplicaCashSearchFromRef.getCurrentData(
              this.$route.query.currency
            )
            this.$refs.ApplicaCashSearchFromRef.settlementList = [
              {
                label: this.query.entCode,
                value: this.query.entId
              }
            ]
            const rows = res.filter(
              (item) => item.currency == this.$route.query.currency
            )
            if (rows.length > 0) {
              let CpoySelectTableData = JSON.parse(JSON.stringify(rows))
              this.tableData.data = CpoySelectTableData
              CpoySelectTableData.forEach((item) => {
                item.getVerificationMoney = item.getUnVerificationMoney
                item.verificationMoney = item.getUnVerificationMoney
                item.x_verificationMoney = item.verificationMoney
                item.xverificationMoney = Math.trunc(
                  item.totalmoney - item.getUnVerificationMoney
                )
                item.getUnVerificationMoney = Math.trunc(
                  item.totalmoney -
                    item.verificationMoney -
                    item.xverificationMoney
                )
                item.x_unVerificationMoney = item.getUnVerificationMoney
              })
              //this.refreshCount(CpoySelectTableData, "searchChange", "settingSumtotalmoney");
            }
          })
      }
    },
    // 保存==
    async saveData(query) {
      query.totalmoney = query.totalmoney ? parseFloat(query.totalmoney) : 0
      let reqData = {
        docReqCashItemList: this.resetFeeList(this.tableData.data),
        ...query,
        id: this.$route.query.id ? this.$route.query.id : 0
      }
      if (query.isDZ) {
        reqData.docCashItemList.forEach((item) => {
          item.workfeeId = item.id
        })
      }
      let res = await this.$http.post('/api/doccash/saveCashReq', reqData)
      if (res.status) {
        if (this.$route.query.qkid) {
          let deatailData = await this.$http.get('/api/doccash/getCashReq', {
            id: res.data
          })
          this.$router.push({
            name: 'ApplicaCashDetail',
            query: {
              id: res.data,
              title: '付款详情' + deatailData.data.doccode,
              iscash: true
            }
          })
        }
        // this.$router.push("/finance/ApplicationFunds");
      } else {
        ElMessage.warning(res.message)
      }
    },
    // //编辑数据刷新
    // editRefresh() {
    //   this.getDetailsData()
    // },
    //搜索内容数据填充
    fillDataByRouter(searchData) {
      let fromQuery = this.$refs.ApplicaCashSearchFromRef.query
      for (const iterator of Object.keys(fromQuery)) {
        fromQuery[iterator] = searchData[iterator]
      }
      fromQuery.feeCurrency = searchData.currency
      fromQuery.paymentType = true
      for (const iterator of searchData.docReqCashItemResDtos) {
        iterator.id = iterator.workfeeId
        iterator.invoiceDate = iterator.invoiceDate
          ? dayjs(iterator.invoiceDate).format('YYYY-MM-DD')
          : ''
        iterator.createtime = iterator.createtime
          ? dayjs(iterator.createtime).format('YYYY-MM-DD HH:mm:ss')
          : ''
      }
      if (this.$route.query.qkid) {
        searchData.docReqCashItemResDtos.forEach((item) => {
          item.payMoney = Number(
            parseFloat(item.totalmoney) - parseFloat(item.hasPayMoney)
          ).toFixed(2)
          item.unPayMoney = Number(
            parseFloat(item.totalmoney) -
              parseFloat(item.hasPayMoney) -
              parseFloat(item.payMoney)
          ).toFixed(2)
        })
      }
      if (this.$route.query.id) {
        fromQuery.doccode = searchData.doccode
        searchData.docReqCashItemResDtos.forEach((item) => {
          item.unPayMoney = Number(
            parseFloat(item.totalmoney) - parseFloat(item.hasPayMoney)
          ).toFixed(2)
          item.hasPayMoney = Number(
            parseFloat(item.hasPayMoney) - parseFloat(item.payMoney)
          ).toFixed(2)
        })
      }

      this.tableData.data = searchData.docReqCashItemResDtos

      this.refreshCount(JSON.parse(JSON.stringify(this.tableData.data)))
    },
    // 刷新页面变动时重新调用接口
    onEarch() {
      this.getDetailsData()
    },
    //从请款页面跳转填充数据
    async getDetailsData() {
      let searchData = {}
      if (this.$route.query.qkid) {
        let qkid = this.$route.query.qkid
        searchData = await this.$http.get('/api/docreqcash/get', {
          id: qkid
        })
        if (!searchData.status) {
          this.$message.warning(searchData.message)
          return
        }
        searchData.data.checkStatus = 0
        this.fillDataByRouter(searchData.data)
        this.$refs.ApplicaCashSearchFromRef.getBankAccount(
          searchData.data.currency
        )
      }

      if (this.$route.query.id) {
        let queryId = this.$route.query.id
        searchData = await this.$http.get('/api/doccash/getCashReq', {
          id: queryId
        })
        if (!searchData.status) {
          this.$message.warning(searchData.message)
          return
        }
        this.$store.dispatch('tab/modifyTabTitle', {
          path: this.$route.fullPath,
          title: this.$route.query.title
        })
        this.fillDataByRouter(searchData.data)
        this.$refs.ApplicaCashSearchFromRef.getBankAccount(
          searchData.data.currency
        )
      }
    }
  },
  watch: {},

  mounted() {
    this.getDetailsData()
  }
})
</script>

<style lang="scss" scoped>
.btn-box {
  margin-bottom: 8px;
}
</style>
